/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;
import models.Quiz;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Vuong Pham<Vuong.Pham@hva.nl>
 */
public class QuizDao {

    private final Session session;

    /*
     * Constructor with session parameter
     */
    public QuizDao(Session session) {
        this.session = session;
    }

    /*
     * Returns list of all quizzes
     */
    public List<Quiz> findAll() {
        Transaction tx = session.beginTransaction();
        List<Quiz> list = session.createQuery("from Quiz as c ORDER BY c.name ASC").list();
        tx.commit();
        return list;
    }

    /*
     * Returns list of all quizzes withing a course
     * parameter id = course id
     */
    public List<Quiz> findAllbyCourse(long id) {
        Transaction tx = session.beginTransaction();
        List<Quiz> list = session.createQuery("from Quiz as c where course_id = " + id + " ORDER BY c.name ASC").list();
        tx.commit();
        return list;
    }

    /*
     * Saves a quiz
     */
    public boolean save(Quiz quiz) {
        try {
            Transaction tx = session.beginTransaction();
            session.save(quiz);
            tx.commit();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /*
     * Updates a quiz
     * returns true if updated
     */
    public boolean update(Quiz quiz) {
        try {
            Transaction tx = session.beginTransaction();
            session.update(quiz);
            tx.commit();
            return true;
        } catch (Exception e) {
            // System.out.println("Error during update: " + e);
            return false;
        }
    }

    /*
     * returns a quiz
     */
    public Quiz get(long id) {
        return (Quiz) session.get(Quiz.class, id);
    }

    /*
     * deletes a quiz
     */
    public void delete(Quiz quiz) {
        Transaction tx = session.beginTransaction();
        session.delete(quiz);
        tx.commit();
    }
}
